package com.llt.common.security.service;

import cn.hutool.core.lang.UUID;
import com.llt.common.core.constants.CacheConstants;
import com.llt.common.core.constants.JwtConstants;
import com.llt.common.core.domain.LoginUser;
import com.llt.common.core.utils.JwtUtils;
import com.llt.common.redis.service.RedisService;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

// 操作登陆 token 的方法
@Slf4j
@Service
@RequiredArgsConstructor
public class TokenService {

    private final RedisService redisService;

    public String createToken(Long userId, String secret, Integer identity, String userName, String headImage) {
        // 生成 token
        Map<String, Object> claim = new HashMap<>();
        String userKey = UUID.fastUUID().toString();
        claim.put(JwtConstants.LOGIN_USER_ID, userId);
        claim.put(JwtConstants.LOGIN_USER_KEY, userKey);
        String token = JwtUtils.createToken(claim, secret);

        // 存储信息到 redis
        String tokenKey = getTokenKey(userKey);

        LoginUser loginUser = new LoginUser();
        loginUser.setIdentity(identity); // 表示是管理员
        loginUser.setUserName(userName);
        loginUser.setHeadImage(headImage);

        redisService.setCacheObject(tokenKey, loginUser, CacheConstants.EXP, TimeUnit.MINUTES);
        return token;
    }

    // 在身份认证通过之后, 业务执行之前执行
    public void extendToken(Claims claims) {
        String userKey = getUserKey(claims);
        if (userKey == null) {
            return;
        }
        String tokenKey = getTokenKey(userKey);

        Long expire = redisService.getExpire(tokenKey, TimeUnit.MINUTES);
        if (expire != null && expire < CacheConstants.REFRESH_TIME) {
            log.info("正在延长 token 过期时间");
            redisService.expire(tokenKey, CacheConstants.EXP, TimeUnit.MINUTES);
        }
    }

    /**
     * 从 redis 中获取用户信息
     */
    public LoginUser getLoginUser(String token, String secret) {
        String userKey = getUserKey(token, secret);
        if (userKey == null) {
            return null;
        }
        return redisService.getCacheObject(getTokenKey(userKey), LoginUser.class);
    }

    /**
     * 从 redis 中删除用户信息 (退出登陆)
     */
    public boolean delete(String token, String secret) {
        String userKey = getUserKey(token, secret);
        if (userKey == null) {
            return false;
        }
        return redisService.deleteObject(getTokenKey(userKey));
    }

    public Long getUserId(Claims claims) {
        if (claims == null) return null;
        return Long.valueOf(JwtUtils.getUserId(claims));  // 获取 jwt 中的 key
    }

    public String getUserKey(Claims claims) {
        if (claims == null) return null;
        return JwtUtils.getUserKey(claims);  //获取jwt中的key
    }

    private String getUserKey(String token, String secret) {
        Claims claims = getClaims(token, secret);
        if (claims == null) return null;
        return JwtUtils.getUserKey(claims);  //获取jwt中的key
    }

    public Claims getClaims(String token, String secret) {
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息  解析payload中信息  存储着用户唯一标识信息
            if (claims == null) {
                log.error("解析token：{}, 出现异常", token);
                return null;
            }
        } catch (Exception e) {
            log.error("解析token：{}, 出现异常", token, e);
            return null;
        }
        return claims;
    }

    public void refreshLoginUser(String nickName, String headImage, String userKey) {
        String tokenKey = getTokenKey(userKey);
        LoginUser loginUser = redisService.getCacheObject(tokenKey, LoginUser.class);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey, loginUser);
    }

    private String getTokenKey(String token) {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }
}
